package com.dwms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dwms.entity.QueryRequest;
import com.dwms.entity.Result;
import com.dwms.entity.api.request.ApiCommonRequest;
import com.dwms.entity.api.response.ApiResponse;
import com.dwms.enums.ResultCode;
import com.dwms.service.GatewayService;
import com.dwms.utils.EmptyUtils;
import com.github.xiaoymin.knife4j.annotations.Ignore;

import com.google.common.collect.Maps;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author WH
 * @className: GatewayController
 * @description: 开放接口
 **/
@Ignore
@Slf4j
@Controller
@RequestMapping(value = "/api/v1/gateway")
public class GatewayController {

    @Resource
    private GatewayService gatewayService;

    /**
     * 订单网关接口
     */
    @RequestMapping
    public void gateway(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            Map<Object, Object> paramMap = Maps.newHashMap();
            Enumeration<String> enumeration = request.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String paramName = enumeration.nextElement();
                String[] values = request.getParameterValues(paramName);
                paramMap.put(paramName, values[0]);
            }
            String value;
            if (EmptyUtils.isNotEmpty(paramMap)) {
                value = JSON.toJSONString(paramMap);
            } else  {
                StringBuilder buffer = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                value = buffer.toString();
            }
            log.info("开放接口请求参数:{}",value);
            ApiCommonRequest apiCommonRequest = JSONObject.parseObject(value, ApiCommonRequest.class);
            Result result = gatewayService.handleApiBusiness(apiCommonRequest);
            log.info("开放接口请求响应:{}",JSON.toJSONString(result));
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(getResult(result));
            response.getWriter().close();
        } catch (Exception e) {
            log.error("开放接口异常", e);
        }
    }

    /**
     * 组装响应结果
     * @param result
     * @return
     */
    private String getResult(Result result) {
        ApiResponse apiResponse = new ApiResponse();
        apiResponse.setType(result.isFailed() ? "error" : "success");
        apiResponse.setContent(result.getMessage());
        return JSON.toJSONString(apiResponse);
    }

}
